package com.nan.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.Date;

import com.nan.common.Md5Util;
import com.nan.common.RespJson;
import com.nan.controller.base.BaseController;
import com.nan.model.UserInfo;

public class UserController extends BaseController {

	public void Login() throws UnsupportedEncodingException {
		String return_uri = getPara("return_uri");
		return_uri = return_uri == null ? "" : URLDecoder.decode(return_uri, "UTF-8");
		setAttr("return_uri", return_uri);
		show("/views/login.jsp");
	}
	
	public void Register() {
		show("/views/register.jsp");
	}
	
	public void LoginCheck() {
		String name = getPara("username").trim();
		String pass = Md5Util.md5(getPara("password"));
		Boolean remember = getParaToBoolean("remember");
		UserInfo user = UserInfo.getOneUserByUname(name);
		if (user == null) {
			showJson(new RespJson(10001, "用户不存在"));
			return ;
		}
		if (pass.equals(user.getPassword())) {
			_saveLoginStatus(remember, user);
			showJson(new RespJson(0, "success"));
			return ;
		}
		showJson(new RespJson(10002, "用户名密码不匹配"));
	}
	
	public void RegCheck(){
		String name = getPara("username").trim();
		String mail = getPara("email").trim();
		String pass = Md5Util.md5(getPara("password"));
		String repass = Md5Util.md5(getPara("repass"));
		Boolean agree = getParaToBoolean("agree");
		if (!agree) {
			showJson(new RespJson(10001, "请同意许可条款"));
			return ;
		}
		if (!pass.equals(repass)) {
			showJson(new RespJson(10002, "两次密码输入不一致"));
			return ;
		}
		if (UserInfo.getOneUserByUname(name) != null) {
			showJson(new RespJson(10003, "用户名已被注册"));
			return ;
		}
		if (UserInfo.getOneUserByEmail(mail) != null) {
			showJson(new RespJson(10004, "邮箱已被注册"));
			return ;
		}

		Date date = new Date();
		Timestamp timestamp = new Timestamp(date.getTime());
		UserInfo user = new UserInfo();
		
		if (user
			.set("type", 0)
			.set("username", name)
			.set("email", mail)
			.set("password", pass)
			.set("regtime", timestamp.getTime() / 1000)
			.set("lasttime", timestamp.getTime() / 1000)
			.save()) {
			showJson(new RespJson(0, "success"));
			return ;
		}
		
		showJson(new RespJson(10005, ""));
		return ;
	}
	
	public void logout()
	{
		setCookie("mm_islogin", "0", 0);
		setCookie("mm_login_user", "0", 0);
		setSessionAttr("mm_islogin", "0");
		setSessionAttr("mm_login_user", null);
		redirect("/");
	}
	
	private void _saveLoginStatus(Boolean remember, UserInfo user) {
		if (remember) {
			setCookie("mm_islogin", "1", 60 * 60 * 24 * 7);
			setCookie("mm_login_user", user.getId().toString(), 60 * 60 * 24 * 7);
		}
		setSessionAttr("mm_islogin", "1");
		setSessionAttr("mm_login_user", user);
	}

}
